<template>
  <div class="page">
    <van-nav-bar title="当前城市 - ">
      <template #left>
        <van-icon name="cross" />
      </template>
    </van-nav-bar>

    <van-search
      v-model="keyword"
      background="#f4f4f4"
      placeholder="输入城市名或拼音"
    />

    <div ref="containerRef" class="container" @scroll="onScroll">
      <section class="section">
        <div class="section-title">GPS定位你所在城市</div>
        <ul>
          <li>
            <div>定位失败</div>
          </li>
        </ul>
      </section>
      <section class="section">
        <div class="section-title">热门城市</div>
        <ul>
          <li
            v-for="item in city.hotCityList"
            :key="item.cityId"
            @click="fn2(item)"
          >
            <div>{{ item.name }}</div>
          </li>
        </ul>
      </section>

      <!-- 分组列表 -->
      <div>
        <section
          class="group"
          v-for="group in city.groups"
          :class="`group-${group.title}`"
          :data-index="group.title"
          :key="group.title"
        >
          <div class="group-title">{{ group.title }}</div>
          <ul>
            <li
              v-for="item in group.list"
              :key="item.cityId"
              @click="fn2(item)"
            >
              {{ item.name }}
            </li>
          </ul>
        </section>
      </div>

      <!-- 拼音检索 -->
      <div class="index">
        <ul>
          <li
            class="index-item"
            v-for="item in city.indexs"
            :class="{ active: curIndex === item }"
            :key="item"
            @click="fn1(item)"
          >
            {{ item }}
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, nextTick } from "vue";
import { useRouter } from "vue-router";
import useStore from "@/hooks/useStore";

const { city } = useStore();
const router = useRouter();

// 搜索关键字
const keyword = ref("");

// 当前高亮显示的首字母
const curIndex = ref("A");
// 当前是否是右侧拼音检索点击
const isFastJump = ref(false);
// container 容器的模板引用
const containerRef = ref<HTMLElement | null>(null);
// 用于存放 group 分组距离 container 容器的距离
//    [{title: 'A', top: 350}, {title: 'B', top: 500}]
const groupEls: { title: string; top: number }[] = [];
let timer: number = 0;
// 右侧拼音检索点击
function fn1(item: string) {
  // 0. 将 curIndex 修改为 item
  curIndex.value = item;
  // 1. 根据 item 去找到 group-${item} 的元素
  const el = document.querySelector<HTMLElement>(`.group-${item}`);
  if (!el) return;
  // 2. 计算该 el 元素 距离 container 元素的 offsetTop .
  //    PS container 元素，需要添加 相对定位
  const offsetTop = el.offsetTop;
  // 3. 修改 container 元素的 scrollTop 值就可以
  if (containerRef.value) {
    isFastJump.value = true;

    // containerRef.value.scrollTop = offsetTop;
    containerRef.value.scrollTo({
      top: offsetTop,
      behavior: "smooth", // 平滑滚动
    });

    clearTimeout(timer);

    timer = setTimeout(() => {
      isFastJump.value = false;
    }, 1000);
  }
}

// container 容器的滚动事件处理函数
function onScroll(e: Event) {
  if (isFastJump.value) return;
  // console.log("onScroll");
  const target = e.target as HTMLDivElement;
  const scrollTop = target.scrollTop;
  // console.log("scrollTop", scrollTop);

  for (let i = groupEls.length - 1; i >= 0; i--) {
    const el = groupEls[i];
    if (scrollTop >= el.top) {
      // 将当前 el.title 赋值给 curIndex
      curIndex.value = el.title;
      break;
    }
  }
}

// 选择城市
function fn2(item: ICity) {
  // 1. 将选择的城市，写入到 store
  city.changeSelectedCity(item);
  // 2. 后退页面，还要判断有没有上一页，如果没有的话，直接去到首页
  if (!history.state.back) {
    router.replace("/");
  } else {
    router.back();
  }
  // console.log("route", route);
  // console.log("router", router);
  // router.back();
}

onMounted(() => {
  city.getCityList().then(() => {
    nextTick(() => {
      document.querySelectorAll<HTMLElement>(".group").forEach((el) => {
        const title = el.getAttribute("data-index") as string;
        const top = el.offsetTop;
        groupEls.push({
          title,
          top,
        });
      });
      // console.log(groupEls);
    });
  });
});
</script>

<style lang="scss" scoped>
.page {
  display: flex;
  flex-direction: column;
}
.container {
  position: relative;
  flex: 1;
  padding-top: 15px;
  overflow-y: auto;
}

.section {
  &-title {
    padding-left: 15px;
    font-size: 14px;
    color: #797d82;
  }
  ul {
    display: flex;
    flex-wrap: wrap;
    padding-left: 15px;
    padding-top: 15px;
  }
  li {
    // padding-left: 15px;
    padding-right: 15px;
    padding-bottom: 15px;
    width: 33.33%;
    box-sizing: border-box;

    // &:nth-child(3n) {
    //   padding-right: 0;
    // }

    div {
      height: 30px;
      line-height: 30px;
      font-size: 14px;
      color: #191a1b;
      text-align: center;
      border-radius: 4px;
      background-color: #f4f4f4;
    }
  }
}

.group {
  &-title {
    padding-left: 15px;
    height: 30px;
    line-height: 30px;
    font-size: 14px;
    color: #000;
    background-color: #ededed;
  }
  ul {
    padding-left: 20px;
  }
  li {
    height: 48px;
    line-height: 48px;
    font-size: 14px;
    color: green;
    &::after {
      content: "";
      display: block;
      width: 100%;
      height: 1px;
      background-color: red;
      transform: scaleY(0.5);
    }
    &:last-child::after {
      display: none;
    }
  }
  &:last-child li:last-child::after {
    display: block;
  }
}

.index {
  display: flex;
  align-items: center;
  margin-top: 100px;
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  width: 18px;
  background-color: green;
  ul {
    width: 100%;
  }
  &-item {
    height: 18px;
    line-height: 18px;
    text-align: center;
    cursor: pointer;
  }
  &-item.active {
    background-color: red;
  }
}
</style>
